﻿package com.firewolf.hibernate.extend.unionsubclass;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class MainDriver {

	private SessionFactory sessionFactory;
	private Session session;
	private Transaction transaction;

	@Before
	public void init() {
		Configuration configuration = new Configuration()
				.configure("com/firewolf/hibernate/extend/unionsubclass/unionsubclass.cfg.xml");
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
				.buildServiceRegistry();
		sessionFactory = configuration.buildSessionFactory(serviceRegistry);

		session = sessionFactory.openSession();
		transaction = session.beginTransaction();
	}

	@After
	public void destroy() {
		transaction.commit();
		session.close();
		sessionFactory.close();
	}

	@Test
	public void testCreate() {
	}

	/**
	 * 新增操作:
	 */
	@Test
	public void testSave() {
		Person person = new Person();
		person.setName("AA");
		person.setAge(1);

		Student student = new Student();
		student.setName("name1");
		student.setAge(2);
		student.setSchool("school1");

		session.save(person);
		session.save(student);
	}

	/**
	 * 更新： 1.若更新父表的字段，则更新的效率较低,因为还要更新子表的
	 */
	@Test
	public void testUpdate() {
		String hql = "update Person p set p.age=20";
		session.createQuery(hql).executeUpdate();

	}

	/**
	 * 查询： 1.查询父类记录（查出来的是父类和子类的），需要把父表和子表合并到一起再查询的，性能较若
	 */
	@Test
	public void testQuery() {
		List<Person> psrsons = session.createQuery("FROM Person").list();
		System.out.println(psrsons.size());

		List<Student> students = session.createQuery("FROM Student").list();
		System.out.println(students.size());
	}
}
